//引入express
import express from "express";
import path from "path";
import { respone } from '../../utils/respone.js'
import { uploadToQiniu } from "../../utils/uploads.js";
import { uploads } from '../../middleware/mluter.js'
import { verifyToken } from '../../middleware/verifyToken.js'
import db from '../../db/index.js'
import { checkallactive } from '../../middleware/checkallactive.js';
const router = express.Router()



// 接受前端录音
router.post('/record', verifyToken, uploads.single('audio'), async (req, res) => {
    try {
        const file = req.file;
        // 生成文件名
        const key = Date.now() + path.extname(file.originalname);
        const { telephone } = req.user;
        // 将本地文件上传到七牛云
        const url = await uploadToQiniu(file.path, key);
        // 插入数据库
        await db('voice').insert({ user_id: result.user_id, telephone, voice_url: url });
        respone(res, 200, '上传成功', { url });
    } catch (error) {
        respone(res, 500, '上传失败', { error: error.message });
    }
})

// 获取所有语音
router.get('/allvoices', verifyToken, checkallactive, async (req, res) => {
    try {
        // 查询数据库
        const result = await db('voice').select();
        respone(res, 200, '获取成功~', { result });
    } catch (error) {
        respone(res, 500, '获取失败', { error: error.message });
    }
})



//暴露路由
export default router;